package com.kelvin.oocl.bookconsumer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

public class BookConsumerImpl implements BookConsumer{
	private Connection connection;
	private String queueName;
	private Session session;
	private MessageConsumer consumer;
	private String mqUrl;
	
	public BookConsumerImpl(String queueName,String mqUrl) {
		this.queueName = queueName;
		this.mqUrl = mqUrl;
		initConsumer();
	}

	private void initConsumer() {
		try {
			ConnectionFactory factory = new ActiveMQConnectionFactory(mqUrl);
			Destination queue = new ActiveMQQueue(queueName);
			connection = factory.createConnection();
			connection.start();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			consumer = session.createConsumer(queue);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void receive(MessageListener listener) throws JMSException {
		consumer.setMessageListener(listener);
	}

	@Override
	public void close() {
		try {
			if(null!=consumer){
				consumer.close();
			}
			if(null!=session){
				session.close();
			}
			if(null!=connection){
				connection.close();
			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
